/**
 * 1、初始化基础数据
 * 2、初始化表格列头
 */

// import Vue from 'vue';
// import VueDraggableResizable from 'vue-draggable-resizable';
// Vue.component('vue-draggable-resizable', VueDraggableResizable);
import DraggableResizable from '../components/draggable-resizable.vue';

export default {
  props: {
    rowSelection: {
      type: Object,
      default: null
    },
    // // 鼠标滚动一次，划过多少行数据，默认三条
    // wheelSpeed: {
    //   type: Number,
    //   default: 3
    // }
    lineScrollBufferCount: {
      // 虚拟滚动buffer
      type: Number,
      default: 40
    }
  },
  components: {
    DraggableResizable
  },
  data() {
    return {
      // 自定义渲染组件
      initBodyCss: ['ant-virtually-table'],
      initTableProps: {},
      initColumnsArray: [],
      selectedAllRowKeys: [],
      selectedAllRows: [],
      bodyTrHeight: 0
      // draggingState: {}
    };
  },
  computed: {
    // rowSelection 如果没有传columnWidth 需要补充一个默认值
    calcRowRelection() {
      let res = undefined;
      if (this.rowSelection) {
        res = { ...this.rowSelection };
        if (!this.rowSelection.columnWidth) {
          res.columnWidth = 60;
        }

        // let onChange = this.rowSelection.onChange;
        res.onSelect = (record, selected, selectedRows, nativeEvent) => {
          this.changeAllRowSelection(record, selected);
          this.rowSelection.onSelect &&
            this.rowSelection.onSelect(record, selected, selectedRows, nativeEvent);
        };
        res.onSelectAll = (dom) => {
          let selected = dom.target.checked;
          this.changeAllRowSelectionSelectAll(selected);
        };
        // onChange 要代理，这里直接删除
        delete res.onChange;
      }
      return res;
    },
    // 行高 需要根据 this.$attrs.size 自行计算
    calcLineHeight() {
      if (this.bodyTrHeight) {
        return this.bodyTrHeight;
      }
      switch (this.$attrs.size) {
        case 'middle':
          return 46;
        case 'small':
          return 38;
        default:
          return 54;
      }
    },
    // 表格数据高度
    tableDataHeight() {
      return this.calcLineHeight * this.dataSource.length;
    },
    calcRowKey() {
      return this.$attrs.rowKey || 'key';
    },
    calcCanSelectDataSource() {
      if (this.rowSelection && this.rowSelection.getCheckboxProps) {
        return this.dataSource.filter((record) => {
          let res = this.rowSelection.getCheckboxProps(record);
          return !(res.props && res.props.disabled);
        });
      } else {
        return this.dataSource;
      }
    },
    calcOpenVirtuallyModel() {
      // 如果是ie
      if (window.document.documentMode) {
        return false;
      } else {
        return this.openVirtuallyModel;
      }
    }
  },
  created() {
    // 更新非响应式数据
    this.table = [];
    this.scrollBarY = 0;
    this.scrollBarX = 0;
    this.scrollBarWidth = 20;
    this.paginationHeight = 50;
    this.mousedownPreventDefault = function (e) {
      e.preventDefault();
    };
    this.clickPreventDefault = function (e) {
      e.preventDefault();
      e.stopPropagation();
    };
    this.init();
    this.initTable();
  },
  mounted() {},
  methods: {
    init() {
      if (this.calcOpenVirtuallyModel) {
        this.initBodyCss.push('ant-virtually-model');
      }
      if (this.isAbsolute) {
        this.initBodyCss.push('ant-virtually-absolute');
      } else {
        this.initBodyCss.push('ant-virtually-def');
      }
      // 默认customRowHandel; 可以设置
      this.initTableProps.customRow = this.customRowHandel;
      // 继承穿透参数
      Object.assign(this.initTableProps, this.$attrs);
    },
    changeAllRowSelection(record, selected) {
      let recordKey = record[this.calcRowKey];
      // 单选
      if (this.calcRowRelection.type === 'radio') {
        if (selected) {
          this.selectedAllRowKeys = [recordKey];
          this.selectedAllRows = [record];
        } else {
          this.selectedAllRowKeys = [];
          this.selectedAllRows = [];
        }
      } else {
        // 复选
        if (selected) {
          this.selectedAllRowKeys = [...new Set([...this.selectedAllRowKeys, recordKey])];
          this.selectedAllRows = [...new Set([...this.selectedAllRows, record])];
        } else {
          this.selectedAllRowKeys = this.selectedAllRowKeys.filter((elKey) => elKey != recordKey);
          this.selectedAllRows = this.selectedAllRows.filter(
            (el) => el[this.calcRowKey] != recordKey
          );
        }
      }
      this.rowSelection.onChange(this.selectedAllRowKeys, this.selectedAllRows);
    },
    changeAllRowSelectionSelectAll(selected) {
      let selectedRows = this.calcCanSelectDataSource;
      let recordKeys = selectedRows.map((el) => el[this.calcRowKey]);
      if (selected) {
        // key去重
        this.selectedAllRowKeys = [...new Set([...this.selectedAllRowKeys, ...recordKeys])];
        // 数据去重
        this.selectedAllRows = [...this.selectedAllRows, ...selectedRows].reduce((acc, cur) => {
          const hasSameItem = acc.some(item => item[this.calcRowKey] === cur[this.calcRowKey])
          if (!hasSameItem) {
            acc.push(cur)
          }
          return acc
        }, [])
        this.rowSelection.onChange(this.selectedAllRowKeys, this.selectedAllRows);
      } else {
        if (this.selectAllPages) {
          // 跨页选择模式，只能清除本业的选中数据
          this.selectedAllRowKeys = this.selectedAllRowKeys.filter(
            (key) => !recordKeys.includes(key)
          );
          this.selectedAllRows = this.selectedAllRows.filter(
            (data) => !selectedRows.includes(data)
          );
        } else {
          const filterCurrentSelectedRowKeys = this.selectedAllRowKeys.filter(item => !recordKeys.includes(item))
          // 适配没有传selectAllPages又没有翻页清空的情况
          if (filterCurrentSelectedRowKeys?.length) {
            // 去重
            this.selectedAllRowKeys = filterCurrentSelectedRowKeys
            this.selectedAllRows = this.selectedAllRows.filter(item => this.selectedAllRowKeys.includes(item[[this.calcRowKey]]))
            this.rowSelection.onChange(this.selectedAllRowKeys, this.selectedAllRows);
          } else {
            this.selectedAllRowKeys = [];
            this.selectedAllRows = [];
            this.rowSelection.selectedRowKeys.length = 0;
            this.rowSelection.onChange([], []);
          }
        }
      }
      this.rowSelection.onSelectAll &&
        this.rowSelection.onSelectAll(selected, this.selectedAllRows);
    },
    cleanSelection() {
      this.selectedAllRowKeys = [];
      this.selectedAllRows = [];
      if (this.rowSelection) {
        if (this.rowSelection.selectedRowKeys) {
          this.rowSelection.selectedRowKeys.length = 0;
        }
        this.rowSelection.onChange && this.rowSelection.onChange([], []);
      }
    },
    cleanRowSelection() {
      this.selectedAllRowKeys = [];
      this.selectedAllRows = [];
      // 清除数组
      this.rowSelection.selectedRowKeys.length = 0;
    },
    initTable() {
      this.initTableColumns();
      // let { initColumnsArray } = this;
      // const draggingMap = {};
      // initColumnsArray.forEach((col) => {
      //   draggingMap[col.key] = col.width;
      // });
      // this.draggingState = Vue.observable(draggingMap);
      if (!this.initTableProps.components) {
        const ResizeableTitle = ({ props, children }) => {
          let thDom = null;
          const { ...restProps } = props;
          const key = props.key;
          let colIndex = 0;
          let columns = this.calcColumns || this.initColumnsArray;
          const col = columns.find((col, index) => {
            const k = col.key;
            if (k === key) {
              colIndex = index;
              return true;
            }
          });
          let style = {};
          let colWidth = null;
          let css = ['resize-table-th'];
          if (col) {
            colWidth = col.width;
            if (col.titleAlign) {
              style.textAlign = col.titleAlign;
            }
            if (col.dropdownMenus) {
              style.paddingRight = '25px';
            }
            col.draggingWidth = 0;
            // 设置sort Css
            if (col.descValue) {
              css.push('table-header-sort-desc');
            }
            if (col.ascValue) {
              css.push('table-header-sort-asc');
            }
            // 如果存在排序
            if (col.dropdownMenus && (col.dropdownMenus.asc || col.dropdownMenus.desc)) {
              css.push('resize-table-th-have-sorter');
            }
          }
          // 没有宽度或者定位在右侧的不能拖
          if (!colWidth || col.fixed === 'right') {
            if (props.key == 'selection-column') {
              css.push('selection-column');
              let checked = false;
              let indeterminate = false;
              if (this.selectedAllRowKeys.length) {
                // 单页筛选模式
                if (
                  !this.selectAllPages &&
                  !this.calcCanSelectDataSource.find(
                    (el) => !this.selectedAllRowKeys.includes(el[this.calcRowKey])
                  )
                ) {
                  checked = true;
                } else if (
                  this.selectAllPages &&
                  !this.calcCanSelectDataSource.find(
                    (el) => !this.selectedAllRowKeys.includes(el[this.calcRowKey])
                  )
                ) {
                  // 跨页筛选模式
                  checked = true;
                } else {
                  checked = false;
                  indeterminate = true;
                }
              } else {
                checked = false;
              }
              // 判断是否选中
              return (
                <th class={css} {...restProps} style={style} title={col && col.title}>
                  {this.calcRowRelection && this.calcRowRelection.type != 'radio' ? (
                    <a-checkbox
                      indeterminate={indeterminate}
                      checked={checked}
                      onChange={this.calcRowRelection.onSelectAll}></a-checkbox>
                  ) : (
                    ''
                  )}
                </th>
              );
            }
            return (
              <th
                class={css}
                {...restProps}
                style={style}
                onClick={this.sortHandel.bind(this, col)}
                title={col && col.title}>
                {children}
              </th>
            );
          }

          const onDrag = (x) => {
            col.draggingWidth = 0;
            if (x === 0) return;
            let colWitdth = Math.max(x, col.minWidth || this.minColumnWidth);
            console.log('onDrag:', colWitdth, col.width);
            if (colWitdth == col.width) {
              return false;
            }
            this.updateTableColumnWidth(col, colWitdth, colIndex);
            if (this.lastNormalCol.key === key) {
              this.$refs.tableScrollX && this.$refs.tableScrollX.scrollToRight();
            } else {
              this.$refs.tableScrollX && this.$refs.tableScrollX.resetScroll();
            }
          };

          const onDragstop = () => {
            col.draggingWidth = thDom.getBoundingClientRect().width;
            this.setDragWidth(col.key, col.width);
            // 重绘
            col.showDragging = false;
            this.$nextTick(() => {
              col.showDragging = true;
              // 更新横向滚动条
              this.initAfterScrollBarX();
              this.initAfterScrollTableBody();
              this.$refs.tableScrollX && this.$refs.tableScrollX.resetScroll();
            });
          };
          const refHandel = (r) => {
            if (r && r.getBoundingClientRect) {
              col.draggingWidth = r.getBoundingClientRect().width;
              let sort = r.querySelector('.ant-table-column-sorter');
              if (sort) {
                sort.innerHTML =
                  '<div class="ant-table-column-sorter-inner ant-table-column-sorter-inner-full"><i aria-label="icon: caret-up" class="anticon anticon-caret-up ant-table-column-sorter-up off"><svg viewBox="0 0 1024 1024" data-icon="caret-up" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z"></path></svg></i><i aria-label="icon: caret-down" class="anticon anticon-caret-down ant-table-column-sorter-down off"><svg viewBox="0 0 1024 1024" data-icon="caret-down" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"></path></svg></i></div>';
              }
            }
            thDom = r;
          };
          return (
            <th
              {...restProps}
              v-ant-ref={refHandel}
              onClick={this.sortHandel.bind(this, col)}
              width={col.width}
              title={col.title}
              style={style}
              class={css}>
              {children}
              {col.showDragging && (
                <DraggableResizable
                  style="heigth: 20px"
                  ref={'draggable-resizable-' + col.key}
                  class="table-draggable-handle"
                  minWidth={80}
                  minX={80}
                  w={10}
                  x={col.draggingWidth || col.width}
                  z={1000}
                  axis="x"
                  active={true}
                  draggable={true}
                  resizable={false}
                  nativeOnMousedown={this.mousedownPreventDefault}
                  nativeOnClick={this.clickPreventDefault}
                  onDragging={onDrag}
                  onDragstop={onDragstop}></DraggableResizable>
              )}
            </th>
          );
        };
        const BodyCell = ({ children, data }) => {
          let title = '';
          if (children.length === 1 && children[0].text) {
            title = children[0].text;
          }
          return (
            <td title={title} class={data.class} style={data.style}>
              {children}
            </td>
          );
        };
        this.initTableProps.components = {
          header: {
            cell: ResizeableTitle
          },
          body: {
            cell: BodyCell
          }
        };
      }
    },
    cleanTableCatch() {
      this.catchColumnsMap = null;
    },
    initTableColumns(isDrag) {
      let { columns } = this;
      // TODO: 没有变化的情况下，不要更新栏目状态
      if (!this.catchColumnsMap) {
        this.initColumnsArray = [];
        this.initColumnsSortMap = {};
        this.catchColumnsMap = {};
        this.fieldsOptionMenus = [];
        this.catchRightDefaultMenusObj = '';
        this.rightColumns = [];
        columns.forEach((col, index) => {
          let cpCol = { ...col };
          cpCol.showDragging = true;
          this.catchColumnsMap[col.key] = cpCol;
          // 补充slot
          if (cpCol.dropdownMenus) {
            cpCol.scopedSlots = col.scopedSlots || {};
            cpCol.scopedSlots.filterDropdown = 'dropdownMenus';
            cpCol.scopedSlots.filterIcon = 'dropdownIcon';
          }
          // 补充属性
          if (cpCol.fixed === undefined) {
            cpCol.fixed = false;
          }
          if (!cpCol.originWidth) {
            cpCol.originWidth = cpCol.width || 'auto';
          }
          if (!cpCol.width) {
            cpCol.width = undefined;
          }
          // 补充筛选字段
          if (cpCol.dropdownMenus) {
            if (cpCol.dropdownMenus.asc === true) {
              cpCol.ascValue = false;
            }
            if (cpCol.dropdownMenus.desc === true) {
              cpCol.descValue = false;
            }
            // cpCol.sortOrder = 'descend';
            // cpCol.defaultSortOrder = 'descend';
            // cpCol.sortDirections = ['descend', 'ascend'];
            // cpCol.sorter = true;
          }
          if (cpCol.fixed !== 'right') {
            // 生成菜单
            this.fieldsOptionMenus.push({
              key: '5-' + index,
              name: cpCol.title,
              colKey: cpCol.key,
              dataIndex: cpCol.dataIndex,
              type: 'switch',
              fixed: cpCol.fixed,
              draggable: true,
              value: true, // 默认选中
              click: () => {}
            });
          } else {
            this.rightColumns.push(cpCol);
          }
          if (cpCol.fixed !== 'right') {
            if (!this.catchRightDefaultMenusObj) {
              this.catchRightDefaultMenusObj = cpCol.key;
            } else {
              this.catchRightDefaultMenusObj = this.catchRightDefaultMenusObj + ',' + cpCol.key;
            }
          }
          this.initColumnsSortMap[cpCol.key] = index;
          this.initColumnsArray.push(cpCol);
          // 初始化缓存的fieldsOptionMenus顺序和选中状态
          this.loadFieldsOptionMenus();
        });
      }
      // 调整显示
      this.initColumnsDisplay();
      // 重新调整顺序
      this.initColumnsSort(isDrag);
    },
    initColumnsDisplay() {
      let showColumns = [];
      if (this.fieldsOptionMenus && this.fieldsOptionMenus.length) {
        this.fieldsOptionMenus.forEach((cld) => {
          if (cld.value) {
            showColumns.push(this.catchColumnsMap[cld.colKey]);
          }
        });
      } else {
        showColumns = this.initColumnsArray;
      }
      this.calcColumns = [...showColumns, ...this.rightColumns];
    },
    initFieldsOptionMenus(col, preSet) {
      let currField = null;
      let normalColumns = [];
      let leftColumns = [];
      // 重新排序
      this.fieldsOptionMenus.forEach((field) => {
        if (field.colKey == col.key) {
          currField = field;
        } else {
          if (field.fixed) {
            leftColumns.push(field);
          } else {
            normalColumns.push(field);
          }
        }
      });
      // 继承冻结
      currField.fixed = col.fixed;
      // 冻结
      if (preSet) {
        this.fieldsOptionMenus = [...leftColumns, currField, ...normalColumns];
      } else {
        // 把currField 还原到 normalColumns: 基于
        // normalColumns = this.initColumnsArray.filter(el=>{
        //   el.
        // })
        //
        normalColumns = [currField, ...normalColumns].sort((a, b) => {
          return this.initColumnsSortMap[a.colKey] - this.initColumnsSortMap[b.colKey];
        });
        this.fieldsOptionMenus = [...leftColumns, ...normalColumns];
      }
      this.catchRightDefaultMenusObj = this.fieldsOptionMenus
        ? this.fieldsOptionMenus
            .filter((el) => el.value)
            .map((el) => el.colKey)
            .join(',')
        : this.catchRightDefaultMenusObj;
    },
    initColumnsSort(isDrag) {
      let { calcColumns } = this;
      // 调整冻结列顺序
      let leftColumns = [];
      let normalColumns = [];
      let rightColumns = this.rightColumns;
      // 获取最后一个fiexd=left的，之前全部为left
      calcColumns.forEach((calcColumn) => {
        if (calcColumn.fixed === 'left') {
          if (isDrag && normalColumns.length) {
            // 全部冻结
            normalColumns.forEach((nCol) => {
              nCol.fixed = 'left';
              leftColumns.push(nCol);
            });
            normalColumns = [];
          }
          leftColumns.push(calcColumn);
        } else if (!this.rightColumns.length && calcColumn.fixed === 'right') {
          rightColumns.push(calcColumn);
        } else if (!calcColumn.fixed) {
          normalColumns.push(calcColumn);
        }
      });
      if (normalColumns.length == 0 && leftColumns.length) {
        let lastLeftColumn = leftColumns.pop();
        if (lastLeftColumn) {
          lastLeftColumn.fixed = null;
          // 回填回去
          normalColumns.push(lastLeftColumn);
        }
      }

      this.leftColumns = leftColumns;
      this.normalColumns = normalColumns;
      this.lastNormalCol = normalColumns[normalColumns.length - 1];
      this.rightColumns = rightColumns;
      // 重新排列normalColumns
      // this.calcColumns = [...leftColumns, ...normalColumns, ...rightColumns];
      this.$nextTick(() => {
        this.initAfterTableHandel();
      });
    }
  },
  beforeDestroy() {}
};
